package org.statemachine.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.config.EnableStateMachine;
import org.springframework.statemachine.config.StateMachineConfigurerAdapter;
import org.springframework.statemachine.config.builders.StateMachineStateConfigurer;
import org.springframework.statemachine.config.builders.StateMachineTransitionConfigurer;
import org.springframework.statemachine.persist.DefaultStateMachinePersister;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.statemachine.domain.Order;

import java.util.EnumSet;

@Configuration
@EnableStateMachine(name = "orderStateMachine")
public class OrderStateMachineConfig extends StateMachineConfigurerAdapter<OrderStatus, OrderEvents> {
    public void configure(StateMachineStateConfigurer<OrderStatus, OrderEvents> states) throws Exception {
        states
                .withStates()
                .initial(OrderStatus.INIT)
                .states(EnumSet.allOf(OrderStatus.class));
    }


    public void configure(StateMachineTransitionConfigurer<OrderStatus, OrderEvents> trasitions) throws Exception {
        trasitions.withExternal().source(OrderStatus.INIT).target(OrderStatus.PAYED)
                .event(OrderEvents.PAY)
                .and()
                .withExternal().source(OrderStatus.PAYED).target(OrderStatus.SHIPPED)
                .event(OrderEvents.SHIP)
                .and()
                .withExternal().source(OrderStatus.SHIPPED).target(OrderStatus.RECIEVED)
                .event(OrderEvents.RECIEVE);


    }


    @Bean
    public DefaultStateMachinePersister persister() {
        return new DefaultStateMachinePersister<>(
                new StateMachinePersist<Object, Object, Order>() {


                    @Override
                    public void write(StateMachineContext<Object, Object> context, Order order) throws Exception {

                    }

                    @Override
                    public StateMachineContext<Object, Object> read(Order order) throws Exception {
                        return new DefaultStateMachineContext<>(order.getStatus(),null,null,null);
                    }
                }


        );
    }


}
